<template>
    <div class="module_main">
        <!-- <live-player video-url="http://192.168.1.11:10080/fvod/GTUGsiqig/video.m3u8"  show-custom-button="true" autoplay="true" aspect="16:9"  resolution="yh,fhd,hd,sd" resolutiondefault="fhd"></live-player> -->
        <div class="safelist-search-container mb-16">
            <a-row class="search-row">
                <a-col class="mr-8">
                    <a-input v-model:value="state.searchData.plateLicense" style="width: 250px;" placeholder="请输入车牌" />
                </a-col>
                <a-col class="mr-8">

                    <a-select v-model:value="state.searchData.manufacturerId" style="width: 200px;" placeholder="全部车企"
                        allowClear>
                        <a-select-option v-for="item in state.manufacturerList" :key="item.id" :value="item.id">
                            {{ item.name }}
                        </a-select-option>
                    </a-select>
                </a-col>

                <a-col>
                    <a-button type="primary" class="mr-8" @click="handleSearch">搜索</a-button>
                    <a-button type="primary" ghost @click="handleEmpty">重置</a-button>
                </a-col>
            </a-row>
            <a-row>

                <a-button type="primary" ghost class="mr-8" style="padding: 0 8px;"
                    @click="handleDownloadQrCode">批量下载二维码</a-button>
                <a-button type="primary" ghost class="mr-8" @click="handleDownloadTemp">下载模板</a-button>

                <a-upload :file-list="state.fileList" :customRequest="handleUpload" action="/attach/upload"
                    :before-upload="beforeUpload">
                    <div>
                        <a-button type="primary" class="mr-8" ghost>批量导入</a-button>
                    </div>
                </a-upload>
                <a-button type="primary" class="mr-8 nmc-add-btn-primary" @click="handleAdd">新增</a-button>
            </a-row>
        </div>
        <div class="safelist-table-container">
            <a-table :columns="tableProps.columns" :data-source="tableProps.dataSource"
                :pagination="tableProps.pagination" :scroll="{ y: 'calc(100vh - 320px)', x: '2000px' }"
                :row-selection="tableProps.rowSelection" :row-key="record => record.id">
                <template #bodyCell="{ column, text, record }">
                    <div v-if="column.key === 'action'" class="action_box">
                        <span @click="viewVehicleDetail(record)">查看详情</span>
                        <span @click="generateQrCode(record)">生成二维码</span>
                        <span @click="editModule(record)">编辑</span>
                        <span class="delete_btn" @click="deleteModule(record)">删除</span>
                    </div>
                    <div v-if="column.dataIndex === 'module_status'" :class="text === 1 ? 'show' : 'none'">
                        {{ text === 1 ? '启用' : '未启用' }}
                    </div>
                    <div v-if="column.dataIndex === 'optStatus'" :class="text === 'Y' ? 'show' : 'none'">
                        {{ text === 'Y' ? '已接入' : '未接入' }}
                    </div>
                </template>
            </a-table>
        </div>
    </div>
    <addModule :manufacturerCompanyOptions="state.manufacturerList"
        :lineOptions="state.lineOptions" ref="addModuleRef" @success="init"></addModule>
    <vehicleDetail ref="vehicleDetailRef" @success="handleDetailSuccess" @realTimeMonitor="handleRealTimeMonitor"
        @historyPlayback="handleHistoryPlayback"></vehicleDetail>
    <a-modal v-model:visible="state.qrCodeVisible" title="查看二维码" width="800px" :show-cancel="false">
        <img :src="state.qrCodeImg" alt="二维码" style="margin: 0 auto;display: block;" />
        <template #footer>
            <a-button key="back" @click="handleCancel">关闭</a-button>
            <a-button key="submit" type="primary" @click="handleDownload">下载</a-button>
        </template>
    </a-modal>
</template>

<script setup>
import { onMounted, reactive, ref, createVNode } from 'vue'
import {
    bizVehicleQueryPage,
    bizVehicleDetail,
    bizVehicleDelete,
    bizVehicleDownloadTemp,
    bizVehicleBatchImport,
    bizVehicleQrcode,bizVehicleZipQrcodes
    //  udmData, udmDeleteData, getQrCode
    // , nmcImport, downloadTemp, zipQrcodes
} from '@/service/nmcApi'
import addModule from './components/addModule.vue'
import vehicleDetail from './components/vehicleDetail.vue'
import { downloadExcelByBlob, downloadZipByBlob } from "@/utils";
import { message, Modal, Upload } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { getManufacturerCompany, getVehicleType, bizLineYunYing } from '@/utils/baseData'
const addModuleRef = ref()
const vehicleDetailRef = ref()
const tableProps = ref({
    columns: [
        {
            title: '',
            dataIndex: 'selection',
            width: 50,
            fixed: 'left'
        },
        {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            customRender: ({ text, record, index, column }) => {
                return (tableProps.value.pagination.current - 1) * tableProps.value.pagination.pageSize + Number(index) + 1;
            }
        },
        {
            title: '车牌',
            dataIndex: 'plateLicense'
        },
        {
            title: '车架号',
            dataIndex: 'plateVin'
        },
        {
            title: '车辆编号',
            dataIndex: 'vehicleCode'
        },
        {
            title: '运营生效时间',
            dataIndex: 'fprq',
            width: 160,
        }, {
            title: '运营截止时间',
            dataIndex: 'sxrq',
            width: 160,
        },
        {
            title: '负责人姓名',
            dataIndex: 'linkman'
        },
        {
            title: '联系电话',
            dataIndex: 'linkTel'
        },
        {
            title: '车企',
            dataIndex: 'manufacturerName'
        },
        {
            title: '车型',
            dataIndex: 'vehicleTypeName'
        },
        {
            title: '运营电子围栏',
            dataIndex: 'fenceName'
        },
        // {
        //     title: '运营商',
        //     dataIndex: 'operatorName'
        // },
        // {
        //     title: '线路名称',
        //     dataIndex: 'lineName'
        // },
        // {
        //     title: '车型',
        //     dataIndex: 'vehicleTypeName'
        // },
        // {
        //     title: '接入状态',
        //     dataIndex: 'optStatus'
        // },
        {
            title: '操作',
            key: 'action',
            width: 320,
            fixed: 'right'
        }
    ],
    dataSource: [],
    rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
            state.selectedRows = selectedRows;
            state.selectedRowKeys = selectedRowKeys;
        }
    },
    pagination: {
        current: 1,
        pageSize: 20,
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `共有${total}条数据`,
        onChange: (current, pageSize) => {
            tableProps.value.pagination.current = current;
            tableProps.value.pagination.pageSize = pageSize;
            init();
        }
    }
})
document.title = '无人车管理平台'
const state = reactive({
    searchData: {  //搜索条件
        likePlateLicense: '',
        manufacturerId: null
    },
    qrCodeImg: '',  //二维码图片
    qrCodeVisible: false, //二维码弹窗
    qrCodeName: '', //二维码名称
    selectedRows: [], //选中行
    selectedRowKeys: [], //选中行key
    fileList: [], //文件列表

    manufacturerCompanyOptions: [], //车企列表
    // vehicleTypeOptions: [], //车型列表
    lineOptions: [], //线路列表
})

// 查看车辆详情
const viewVehicleDetail = (record) => {
    bizVehicleDetail({ id: record.id }).then(res => {
        console.log(res, 'res');
        if (res.status =='000_0000_0000') {
            vehicleDetailRef.value.showModal({
                title: '车辆详情',
                ...res.result
            })
        }
    })
}

// 处理详情弹窗确认
const handleDetailSuccess = (data) => {
    console.log('车辆详情确认:', data)
    message.success('操作成功')
}

// 处理实时监控
const handleRealTimeMonitor = (data) => {
    console.log('实时监控:', data)
    // 这里可以跳转到实时监控页面或打开监控弹窗
}

// 处理历史回放
const handleHistoryPlayback = (data) => {
    console.log('历史回放:', data)
    // 这里可以跳转到历史回放页面或打开回放弹窗
}

// 下载模板
const handleDownloadTemp = () => {
    bizVehicleDownloadTemp().then(res => {
        downloadExcelByBlob(res, '无人车导入模板.xls')
    })
}
// 批量下载二维码
const handleDownloadQrCode = () => {
    console.log(state.selectedRows, 'state.selectedRows');
    if (state.selectedRows.length === 0) {
        message.warning('请选择要下载二维码的车辆')
        return
    }
    let ids = state.selectedRows.map(item => item.id).join(',')
    bizVehicleZipQrcodes({ vehicleIds: ids }).then(res => {
        // console.log(res, 'res');
        downloadZipByBlob(res, '车辆二维码.zip')
    })
}

const handleUpload = (file) => {
    const data = new FormData();
    data.append('file', file.file)
    bizVehicleBatchImport(data).then(res => {
        // console.log(res, 'res');
        if (res.status =='000_0000_0000') {
            message.success('导入成功')
            init()
        }
    })
}
// 上传前座验证
const beforeUpload = async (file) => {
    console.log(file, 'file');
    if (file.type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        && file.type != 'application/vnd.ms-excel') {
        message.warning('上传文件只能是xlsx或xls')
        return false || Upload.LIST_IGNORE;
    }
}
// 生成二维码
const generateQrCode = (record) => {
    console.log(record, 'record');
    bizVehicleQrcode(record.id).then(res => {
        console.log(res, 'res');
        if (res.status =='000_0000_0000') {
            state.qrCodeVisible = true
            state.qrCodeImg = res.result
            state.qrCodeName = record.plateLicense
        }
    })
}
// 关闭二维码
const handleCancel = () => {
    state.qrCodeVisible = false
}
// 弹窗 下载二维码
const handleDownload = () => {
    const link = document.createElement('a')
    link.href = state.qrCodeImg
    link.download = `车辆二维码_${state.qrCodeName}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}
const init = () => {
    let params = {
        ...state.searchData,
        start: tableProps.value.pagination.current,
        limit: tableProps.value.pagination.pageSize,
    }
    bizVehicleQueryPage(params).then(res => {
        console.log(res, 'res');
        if (res.status === "000_0000_0000") {
            tableProps.value.dataSource = res.result.list;
            console.log(res.result, 'res.data.result');

            tableProps.value.pagination.total = Number(res.result.total)
        }
    })
}

const handleSearch = () => {
    tableProps.value.pagination.current = 1;
    init()
}

const handleEmpty = () => {
    state.searchData = {
        likePlateLicense: '',
        manufacturerId: null
    }
    init()
}

const handleAdd = () => {
    // console.log(addModuleRef.value, 'addModuleRef.value');

    addModuleRef.value.showModal({
        title: '新增车辆'
    })
}



const editModule = (record) => {
    addModuleRef.value.showModal({
        title: '编辑车辆',
        ...record
    })
}

const deleteModule = (record) => {
    Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '您是否要删除当前车辆？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
            return new Promise((resolve, reject) => {
                    bizVehicleDelete({ id: record.id }).then(res => {
                        if (res.status =='000_0000_0000') {
                            message.success('删除成功!')
                            init()
                            resolve()
                        }
                    }).catch(err => {
                        resolve()
                        // message.error(err.message);
                    })

            })
        },
    });
}

onMounted(async () => {
    init()
    state.manufacturerList = await getManufacturerCompany()
    // console.log(state.manufacturerList, 'manufacturerList');
    // state.vehicleTypeOptions = await getVehicleType()
    state.lineOptions = await bizLineYunYing()
    // console.log(state.vehicleTypeOptions, 'vehicleTypeOptions');
})
</script>

<style lang="less" scoped>
.module_main {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.safelist-table-container {
    height: calc(100% - 48px);
    overflow: hidden;

    .action_box {
        display: flex;
        font-size: 14px;
        color: #00CCCC;

        span {
            cursor: pointer;
            margin-right: 8px;
        }

        .delete_btn {
            color: rgba(255, 47, 0, 1);
        }
    }

    .show {
        width: 40px;
        height: 18px;
        background: #0E3E6C;
        border-radius: 4px;
        color: rgba(36, 195, 142, 1);
        line-height: 18px;
        text-align: center;
    }

    .none {
        width: 60px;
        height: 18px;
        background: rgba(255, 255, 255, 0.14);
        border-radius: 4px;
        line-height: 18px;
        text-align: center;
        color: rgba(255, 255, 255, 0.25);
    }
}
</style>